<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="数据日期" :required="true">
              <j-date placeholder="请选择数据日期" v-model="queryParam.sjrq"></j-date>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="主题">
              <j-tree-select
                ref="treeSelect"
                placeholder="请选择主题"
                v-model="queryParam.theme"
                dict="llbb_param_config,name,code"
                pidValue="1506488476828733442"
                hasChildField="has_child"
              >
              </j-tree-select>
            </a-form-item>
          </a-col>
          <a-col :xl="12" :lg="7" :md="8" :sm="24">
            <a-form-item label="报文名称">
              <j-search-select-tag
                placeholder="请选择报文名称"
                v-model="queryParam.reportId"
                dict="llbb_message_forms,reporttypename,reporttypecode"
                :pageSize="null">
              </j-search-select-tag>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="数据生成状态">
                <j-dict-select-tag placeholder="请选择数据生成状态" v-model="queryParam.dataStatus" dictCode="datastatus"/>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="校验状态">
                <j-dict-select-tag placeholder="请选择校验状态" v-model="queryParam.verifyStatus" dictCode="verify_status1"/>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="锁库状态">
                <j-dict-select-tag placeholder="请选择锁库状态" v-model="queryParam.lockFlag" dictCode="lock_flag"/>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleCreate" type="primary">上报数据生成</a-button>
      <a-button @click="handleVerify" type="primary">上报数据校验</a-button>
      <a-button @click="handleSelLock" type="primary">锁库</a-button>
      <a-button @click="handleItemLock" type="primary">强制锁库</a-button>
      <a-button @click="handleSelUnLock" type="primary">批量解库</a-button>
      <a-button @click="reportDataCreate" type="primary">存保数据生成</a-button>
<!--      <a-button @click="handleBack" type="primary">批量打回</a-button>-->
<!--      <a-button @click="handleAddend" type="primary">批量补录</a-button>-->
    </div>

    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
        <span slot="unlock" slot-scope="text, record">
          <a v-if="text=='1'" @click="handleUnlock(record)" >解锁</a>
          <a v-else-if="text=='2'" @click="handleUnlock(record)" >解锁</a>
          <span v-else >解锁</span>
        </span>
        <span slot="back" slot-scope="text, record">
          <!--
          <span v-if="record.createFile==null" >打回重报</span>
          <span v-else-if="record.createFile==''" >解锁</span>
          <a v-else @click="handleBackInfo(record)">打回重报</a>
          -->
          <a @click="handleBackInfo(record)">打回重报</a>
        </span>
        <span slot="reportName" slot-scope="text, record">
          <a @click="handleShow(record)">{{ text }}</a>
        </span>
        <template slot="createFile" slot-scope="text, record">
          <span v-if="!text||text===''" >无</span>
          <a v-else :ghost="true" @click="downCreate(record)">查看错误（txt）</a>
        </template>
        <template slot="verifyFile" slot-scope="text, record">
          <span v-if="!text||text===''" >无</span>
          <a v-else :ghost="true" @click="downVerify(record)">查看错误（log）</a>
        </template>
      </a-table>
    </div>

    <llbb-message-status-modal ref="modalForm" @ok="modalFormOk"></llbb-message-status-modal>
    <HandelBackModal ref="handelBack" @ok="modalFormOk"></HandelBackModal>
    <view-model ref="vmodel"></view-model>
    <j-modal
      :visible.sync="jmodal.visible"
      :width="600"
      :title="jmodal.title"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-textarea
        v-model="jmodal.remark"
        placeholder="请输入强制锁库理由"
        maxLength="200"
        :auto-size="{ minRows: 6, maxRows: 12}"
      />
    </j-modal>
    <j-modal
      :visible.sync="modal.visible"
      :width="600"
      :title="modal.title"
      :fullscreen.sync="modal.fullscreen"
      :switchFullscreen="modal.switchFullscreen"
    >
      <template v-for="(i,k) in dataList">
        <p :key="k">{{i}}</p>
      </template>
      <template slot="footer">
        <a-button @click="this.closeWindow" type="primary">关闭</a-button>
      </template>
    </j-modal>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import LlbbMessageStatusModal from './modules/LlbbMessageStatusModal'
  import ViewModel from './modules/ViewModel'
  import Vue from 'vue'
  import axios from 'axios';
  Vue.prototype.$axios = axios;
  import {getAction} from '@/api/manage'
  import { ACCESS_TOKEN} from "@/store/mutation-types"
  import HandelBackModal from './backInfo/HandelBackModal'
  export default {
    name: 'LlbbMessageStatusList',
    mixins:[JeecgListMixin, mixinDevice],
    components: {
      ViewModel,
      LlbbMessageStatusModal,
      HandelBackModal,
    },
    data () {
      return {
        description: '报表状态表管理页面',
        queryParam: {
          sjrq: "",
          theme:"",
        },
        jmodal:{
          "visible":false,
          "title":"强制锁库",
          "remark":""
        },
        modal: {
          title: '未提交业务表',
          visible: false,
          fullscreen: false,
          switchFullscreen: false,
        },
        dataList:[],
        // 表头
        columns: [
          {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'数据日期',
            align:"center",
            dataIndex: 'sjrq',
            customRender:function (text) {
              return !text?"":(text.length>10?text.substr(0,10):text)
            }
          },
          {
            title:'报文名称',
            align:"center",
            dataIndex: 'reportId_dictText',
            scopedSlots: {customRender: 'reportName'},
          },
          {
            title:'主题分类',
            align:"center",
            dataIndex: 'theme_dictText'
          },
          {
            title:'频度',
            align:"center",
            dataIndex: 'frequency_dictText'
          },
          // {
          //   title:'是否可生成',
          //   align:"center",
          //   dataIndex: 'createFlag_dictText'
          // },
          {
            title:'是否可校验',
            align:"center",
            dataIndex: 'verifyFlag_dictText'
          },
          {
            title:'数据生成状态',
            align:"center",
            dataIndex: 'dataStatus_dictText'
          },
          {
            title:'校验状态',
            align:"center",
            dataIndex: 'verifyStatus_dictText'
          },
          {
            title:'锁库状态',
            align:"center",
            dataIndex: 'lockFlag_dictText'
          },
          {
            title:'生成错误',
            align:"center",
            dataIndex: 'createFile',
            scopedSlots: {customRender: 'createFile'}
          },
          {
            title:'校验错误',
            align:"center",
            dataIndex: 'verifyFile',
            scopedSlots: {customRender: 'verifyFile'}
          },
          {
            title:'强制锁库原因',
            align:"center",
            dataIndex: 'lockRemark'
          },
          {
            title:'生成操作',
            dataIndex: 'lockFlag',
            scopedSlots: {customRender: 'unlock'},
            align: "center",
            fixed:"right",
            width: 90
          },
          {
            title:'补录操作',
            dataIndex: 'back',
            scopedSlots: {customRender: 'back'},
            align: "center",
            fixed:"right",
            width: 90
          }
        ],
        url: {
          list: "/llbbMessageStatus/llbbMessageStatus/list",
          delete: "/llbbMessageStatus/llbbMessageStatus/delete",
          deleteBatch: "/llbbMessageStatus/llbbMessageStatus/deleteBatch",
          exportXlsUrl: "/llbbMessageStatus/llbbMessageStatus/exportXls",
          importExcelUrl: "llbbMessageStatus/llbbMessageStatus/importExcel",

        },
        dictOptions:{},
        superFieldList:[],
      }
    },
    created() {
      this.getSuperFieldList();
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      initDictConfig(){
      },
      handleAddend(){
        const that = this;
        if(this.selectedRowKeys.length==0){
          that.$message.warning("请选择你要处理的数据");
          return false;
        }
        this.checkPagam={
          ids:this.selectedRowKeys
        }
        let url="/llbbMessageStatus/llbbMessageStatus/addend";
        this.loading = true;
        getAction(url,this.checkPagam).then((res)=>{
          that.onClearSelected();
          that.loading = false;
          if(res.success){
            that.$message.success(res.message);
            that.loadData(1);
          }else{
            that.$message.warning(res.message);
          }
        }).finally(() => {
        })
      },
      reportDataCreate(){
        const that = this;
        if(this.queryParam.sjrq==''){
          that.$message.warning("请选择你要生成数据的日期");
          return false;
        }
        let url="/llbbMessageStatus/llbbMessageStatus/reportDataCreate";
        this.loading = true;
        getAction(url,this.queryParam).then((res)=>{
          that.onClearSelected();
          that.loading = false;
          if(res.success){
            that.$message.success(res.message);
            that.loadData(1);
          }else{
            that.$message.warning(res.message);
          }
        }).finally(() => {
        })
      },
      handleCreate(){
        const that = this;
        if(this.selectedRowKeys.length==0){
          that.$message.warning("请选择你要处理的数据");
          return false;
        }
        for(var i=0;i<this.selectionRows.length;i++){
          //锁库状态，0-未锁库，1-已锁库，2-已锁库（强制锁库）,3-已解锁
          var lockFlag = this.selectionRows[i].lockFlag;
          if("1" == lockFlag || "2" == lockFlag){
            this.$message.warning("已锁库,数据不可操作！");
            return;
          }
        }
        this.checkPagam={
          ids:this.selectedRowKeys
        }
        let url="/llbbMessageStatus/llbbMessageStatus/createInfo";
        this.loading = true;
        getAction(url,this.checkPagam).then((res)=>{
          that.onClearSelected();
          that.loading = false;
          if(res.success){
            that.$message.success(res.message);
            that.loadData(1);
          }else if(res.code == 501){
            console.log(res);
            this.dataList=res.result;
            this.modal.title='未提交业务表';
            this.modal.visible=true;
          }else{
            that.$message.warning(res.message);
          }
        }).finally(() => {
        })
      },
      handleOk(){
        if(this.jmodal.remark==''){
          that.$message.warning("请输入强制锁库理由");
          return false;
        }
        this.checkPagam={
          ids:this.selectedRowKeys,
          remark:this.jmodal.remark
        }
        const that = this;
        let url="/llbbMessageStatus/llbbMessageStatus/itemLock";
        this.loading = true;
        getAction(url,this.checkPagam).then((res)=>{
          that.onClearSelected();
          that.loading = false;
          if(res.success){
            that.$message.success(res.message);
            that.loadData(1);
          }else{
            that.$message.warning(res.message);
          }
        }).finally(() => {
        })
      },
      handleCancel(){
        this.jmodal.visible=false;
      },
      handleShow(record){
        this.$refs.vmodel.show(record);
      },
      handleVerify(){
        //数据校验
        if(this.selectedRowKeys.length == 0){
          this.$message.warning("请选择你要处理的数据");
          return;
        }
        var ids = "";
        for(var i=0;i<this.selectionRows.length;i++){
          ids += this.selectionRows[i].id + ",";
          //数据状态。0-无1-未生成2-已生成，有错误3-已生成，无错误
          var dataStatus = this.selectionRows[i].dataStatus;
          //锁库状态，0-未锁库，1-已锁库，2-已锁库（强制锁库）,3-已解锁
          var lockFlag = this.selectionRows[i].lockFlag;
          //是否可校验，0-否，1-是
          var verifyFlag = this.selectionRows[i].verifyFlag;
          if("1" == lockFlag || "2" == lockFlag){
            this.$message.warning("已锁库,数据不可操作！");
            return;
          }
          if("3" != dataStatus){
            this.$message.warning("报文数据未生成,数据不可校验！");
            return;
          }
          if("0" == verifyFlag){
            this.$message.warning("数据不可校验！");
            return;
          }
        }
        let url = "/verificationresult/llbbVerificationResult/messageDataCheck";
        let checkPagam = {"ids":ids};
        this.loading = true;
        const that = this;
        getAction(url,checkPagam).then((res)=>{
          if(res.success){
            that.$message.success(res.message);
            that.loadData(1);
          }else{
            that.$message.warning(res.message);
          }
        }).finally(() => {
          that.onClearSelected();
          that.loading = false;
        });
      },
      handleSelLock(){
        const that = this;
        if(this.selectedRowKeys.length==0){
          that.$message.warning("请选择你要处理的数据");
          return false;
        }
        for(var i=0;i<this.selectionRows.length;i++){
          //校验状态。1-未校验2-已校验有误3-已校验无误
          var verifyStatus = this.selectionRows[i].verifyStatus;
          if("1" == verifyStatus){
            this.$message.warning("存在未校验数据,不可锁库！");
            return;
          }else if("2" == verifyStatus){
            this.$message.warning("存在校验未通过数据,不可锁库！");
            return;
          }
        }
        //this.jmodal.visible=true;
        let url="/llbbMessageStatus/llbbMessageStatus/lockKu";
        this.loading = true;
        getAction(url,{ids:this.selectedRowKeys}).then((res)=>{
          this.onClearSelected();
          this.loading = false;
          if(res.success){
            this.$message.success(res.message);
            this.loadData(1);
          }else{
            this.$message.warning(res.message);
          }
        }).finally(() => {
        });
      },
      handleItemLock(){
        //强制锁库
        if(this.selectedRowKeys.length==0){
          that.$message.warning("请选择你要处理的数据");
          return false;
        }
        for(var i=0;i<this.selectionRows.length;i++){
          //校验状态。1-未校验2-已校验有误3-已校验无误
          var verifyStatus = this.selectionRows[i].verifyStatus;
          if("1" == verifyStatus){
            this.$message.warning("存在未校验数据,不可锁库！");
            return;
          }
        }
        this.jmodal.visible=true;
      },
      handleSelUnLock(){
        const that = this;
        if(this.selectedRowKeys.length==0){
          that.$message.warning("请选择你要处理的数据");
          return false;
        }
        this.checkPagam={
          ids:this.selectedRowKeys
        }
        let url="/llbbMessageStatus/llbbMessageStatus/itemUnLock";
        this.loading = true;
        getAction(url,this.checkPagam).then((res)=>{
          that.onClearSelected();
          that.loading = false;
          console.log(res)
          if(res.success){
            that.$message.success(res.message);
            that.loadData(1);
          }else{
            that.$message.warning(res.message);
          }
        }).finally(() => {
        })
      },
      handleBack(){
        const that = this;
        if(this.selectedRowKeys.length==0){
          that.$message.warning("请选择你要处理的数据");
          return false;
        }
        this.checkPagam={
          ids:this.selectedRowKeys
        }
        let url="/llbbMessageStatus/llbbMessageStatus/back";
        this.loading = true;
        getAction(url,this.checkPagam).then((res)=>{
          that.onClearSelected();
          that.loading = false;
          if(res.success){
            that.$message.success(res.message);
            that.loadData(1);
          }else{
            that.$message.warning(res.message);
          }
        }).finally(() => {
        })
      },
      handleUnlock(record){
        console.log(record);
        this.checkPagam={
          ids:[record.id]
        }
        const that = this;
        let url="/llbbMessageStatus/llbbMessageStatus/itemUnLock";
        this.loading = true;
        getAction(url,this.checkPagam).then((res)=>{
          that.onClearSelected();
          that.loading = false;
          if(res.success){
            that.$message.success(res.message);
            that.loadData(1);
          }else{
            that.$message.warning(res.message);
          }
        }).finally(() => {
        })
      },
      handleBackInfo(record){
        //锁库状态，0-未锁库，1-已锁库，2-已锁库（强制锁库）,3-已解锁
        var lockFlag = record.lockFlag;
        if("1" == lockFlag || "2" == lockFlag){
          this.$message.warning("已锁库,数据不可操作！");
          return;
        }
        this.$refs.handelBack.title = "打回重报";
        this.$refs.handelBack.show(record);
        this.$refs.handelBack.disableSubmit = true;
        /**
        const that = this;
        this.checkPagam={
          ids:[record.id]
        }
        let url="/llbbMessageStatus/llbbMessageStatus/back";
        this.loading = true;
        getAction(url,this.checkPagam).then((res)=>{
          that.onClearSelected();
          that.loading = false;
          if(res.success){
            that.$message.success(res.message);
            that.loadData(1);
          }else{
            that.$message.warning(res.message);
          }
        }).finally(() => {
        })
         */
      },
      downCreate(record){
        let id=record.id;
        this.$axios({
          method: "get",
          url: `${window._CONFIG['domianURL']}/llbbMessageStatus/llbbMessageStatus/downCreate?id=`+id,
          responseType: "blob",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            'X-Access-Token':Vue.ls.get(ACCESS_TOKEN)
          },
        }).then(function (response) {
            //下载
            var reader = new FileReader();
            reader.onload = (e) => {
              //下载
              let data = response.data;
              if (!data) {
                return;
              }
              var blob = new Blob([data], {
                type: "text/plain;charset=UTF-8",
              });
              var url = window.URL.createObjectURL(blob);
              var aLink = document.createElement("a");
              aLink.style.display = "none";
              aLink.href = url;
              aLink.setAttribute("download", "生成错误.txt");
              document.body.appendChild(aLink);
              aLink.click();
              //下载完成移除元素
              document.body.removeChild(aLink);
              //释放掉blob对象
              window.URL.revokeObjectURL(url);
            };
            reader.readAsText(response.data);
          })
          .catch(function (error) {
            console.log(error);
          });
      },
      downVerify(record){
        var id=record.id;
        this.$axios({
          method: "get",
          url: `${window._CONFIG['domianURL']}/llbbMessageStatus/llbbMessageStatus/downVerify?id=`+id,
          responseType: "blob",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            'X-Access-Token':Vue.ls.get(ACCESS_TOKEN)
          },
        }).then(function (response) {
          //下载
          var reader = new FileReader();
          reader.onload = (e) => {
            console.log("开始下载");
            //下载
            let data = response.data;
            if (!data) {
              return;
            }
            var blob = new Blob([data], {
              type: "text/plain;charset=UTF-8",
            });
            var url = window.URL.createObjectURL(blob);
            var aLink = document.createElement("a");
            aLink.style.display = "none";
            aLink.href = url;
            aLink.setAttribute("download", "校验错误.log");
            document.body.appendChild(aLink);
            aLink.click();
            //下载完成移除元素
            document.body.removeChild(aLink);
            //释放掉blob对象
            window.URL.revokeObjectURL(url);
          };
          reader.readAsText(response.data);
        }).catch(function (error) {
            console.log(error);
        });
      },
      closeWindow(){
        this.modal.visible=false;
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'bankNoCd',text:'法人标识'})
        fieldList.push({type:'string',value:'devideCls',text:'权限划分类别。按固定依据划分数据权限：1-角色2-机构3-用户'})
        fieldList.push({type:'string',value:'bankCode',text:'分支机构编码'})
        fieldList.push({type:'string',value:'reportId',text:'报表id'})
        fieldList.push({type:'string',value:'dataStatus',text:'数据状态。1-未生成2-已生成有误3-已生成成功'})
        fieldList.push({type:'string',value:'verifyStatus',text:'校验状态。1-未校验2-已校验有误3-已校验无误'})
        fieldList.push({type:'date',value:'sjrq',text:'数据日期'})
        fieldList.push({type:'string',value:'ifCommit',text:'是否强制提交:0-否,1-是'})
        fieldList.push({type:'string',value:'ifVerify',text:'是否强制校验:0-否,1-是'})
        fieldList.push({type:'string',value:'lastdayPerson',text:'上一日提交人'})
        fieldList.push({type:'string',value:'roleId',text:'角色id'})
        fieldList.push({type:'string',value:'createFlag',text:'是否可生成，0-否，1-是'})
        fieldList.push({type:'string',value:'verifyFlag',text:'是否可校验，0-否，1-是'})
        fieldList.push({type:'string',value:'theme',text:'主题'})
        fieldList.push({type:'string',value:'lockFlag',text:'锁库状态，0-未锁库，1-已锁库，2-已锁库（强制锁库）,3-已解锁'})
        this.superFieldList = fieldList
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>